﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.Runtime.Serialization;
using first_learn.GeocodeService;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Text;

namespace first_learn
{
    
    public partial class MainPage : PhoneApplicationPage
    {

        GeoCoordinateWatcher watcher;
        string accuracyText = "";
        string address = "";
        double latitude = 0;
        double longitude = 0;

        Socket s = null;
        static ManualResetEvent done = new ManualResetEvent(false);

        #region Initialization
        public MainPage()
        {
            InitializeComponent();
        }
        #endregion

        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {

        }

        #region User Interface
        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            StartLocationService(GeoPositionAccuracy.Default);
        }
        #endregion


        public static Guid GetId()
        {
            Guid applicationId = Guid.Empty;

            var productId = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("ProductID");

            if (productId != null && !string.IsNullOrEmpty(productId.Value))
                Guid.TryParse(productId.Value, out applicationId);

            return applicationId;
        }

        #region Application logic




        /// <summary>
        /// Helper method to start up the location data acquisition
        /// </summary>
        /// <param name="accuracy">The accuracy level </param>
        private void StartLocationService(GeoPositionAccuracy accuracy)
        {
            // Reinitialize the GeoCoordinateWatcher
            watcher = new GeoCoordinateWatcher(accuracy);
            watcher.MovementThreshold = 20;

            // Add event handlers for StatusChanged and PositionChanged events
            watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);

            // Start data acquisition
            watcher.Start();
        }

        /// <summary>
        /// Handler for the StatusChanged event. This invokes MyStatusChanged on the UI thread and
        /// passes the GeoPositionStatusChangedEventArgs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyStatusChanged(e));
        }
        /// <summary>
        /// Custom method called from the StatusChanged event handler
        /// </summary>
        /// <param name="e"></param>
        void MyStatusChanged(GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    // The location service is disabled or unsupported.
                    // Alert the user
                    //StatusTextBlock.Text = "location is unsupported on this device";
                    break;
                case GeoPositionStatus.Initializing:
                    // The location service is initializing.
                    // Disable the Start Location button
                    //StatusTextBlock.Text = "initializing location service," + accuracyText;
                    break;
                case GeoPositionStatus.NoData:
                    // The location service is working, but it cannot get location data
                    // Alert the user and enable the Stop Location button
                    //StatusTextBlock.Text = "data unavailable," + accuracyText;
                    break;
                case GeoPositionStatus.Ready:
                    // The location service is working and is receiving location data
                    // Show the current position and enable the Stop Location button
                    //StatusTextBlock.Text = "receiving data, " + accuracyText;
                    break;

            }
        }

        /// <summary>
        /// Handler for the PositionChanged event. This invokes MyStatusChanged on the UI thread and
        /// passes the GeoPositionStatusChangedEventArgs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyPositionChanged(e));
        }

        /// <summary>
        /// Custom method called from the PositionChanged event handler
        /// </summary>
        /// <param name="e"></param>
        void MyPositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            // Update the TextBlocks to show the current location
            textBox1.Text = e.Position.Location.Latitude.ToString("0.000");
            textBox2.Text = e.Position.Location.Longitude.ToString("0.000");
            latitude = e.Position.Location.Latitude;
            longitude = e.Position.Location.Longitude;
            GeocodeServiceClient client = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");

            client.ReverseGeocodeCompleted += new EventHandler<ReverseGeocodeCompletedEventArgs>(OnReverseGeocodeCompleted);

            ReverseGeocodeRequest request = new ReverseGeocodeRequest();
            request.Credentials = new first_learn.GeocodeService.Credentials();
            request.Credentials.ApplicationId = "AjjGZGtCVs7lEuRn860kGigumg5hhJ8LqKXOIxpk1zwuxxQUgcrFDRWmrYfYCtFg";
            Location loc = new Location();
            loc.Latitude = e.Position.Location.Latitude;
            loc.Longitude = e.Position.Location.Longitude;
            request.Location = loc;
            client.ReverseGeocodeAsync(request); 
        }

        private void OnReverseGeocodeCompleted(object sender, ReverseGeocodeCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Results.Count >= 0)
                {
                    GeocodeResponse response = e.Result;

                    address = response.Results[0].DisplayName;
                    textBox3.Text = address;
                    
                    //System.Collections.ObjectModel.ObservableCollection<GeocodeResult> list = response.Results;
                    //string allName = "";
                    //foreach (GeocodeResult i in list)
                    //{
                    //    allName += i.DisplayName + "  ";
                    //}
                    //textBox3.Text = allName;
                }
                else
                    MessageBox.Show("Sorry, cannot find location!");
            }
        }  

        #endregion

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            string msg = address;
            ServiceReference1.Service1Client myClient = new ServiceReference1.Service1Client();
            myClient.GetDataCompleted += new EventHandler<ServiceReference1.GetDataCompletedEventArgs>(myClient_GetDataCompleted);
            myClient.GetDataAsync((int)latitude);
        }

        void myClient_GetDataCompleted(object sender, ServiceReference1.GetDataCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
        }

    }
}